package controller;

import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import po.Message;
import websocket.MyWebSocketHandler;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

@Controller
public class ChatController {
	@Autowired
    MyWebSocketHandler handler;
	

	@RequestMapping("/onlineusers")
	@ResponseBody
	public Set<String> onlineusers(HttpSession session){
		Map<String, WebSocketSession> map=MyWebSocketHandler.userSocketSessionMap;
		Set<String> set=map.keySet();
		Iterator<String> it = set.iterator();
		Set<String> nameset=new HashSet<String>();
		while(it.hasNext()){
			String username = it.next();
			String user=(String)session.getAttribute(username);
//			if(!username.equals(user))
			nameset.add(username);
		}
		return nameset;
	}
	
	// 发布系统广播（群发）
		@ResponseBody
		@RequestMapping(value = "broadcast", method = RequestMethod.POST)
		public void broadcast(@RequestParam("text") String text) throws IOException {
			Message msg = new Message();
			msg.setDate(new Date());
			msg.setFrom(-1L);//-1表示系统广播
			msg.setFromName("系统广播");
			msg.setTo(0L);
			msg.setText(text);
			handler.broadcast(new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(msg)));
		}
		

}
